package action

import (
	"errors"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/session"
	"teamcoop/global"
	. "teamcoop/models"
)

func AnnouncePublish(sid string, text string) (aid int64, err error) {
	//获取session
	var sessions session.SessionStore
	sessions, err = global.MySessions.GetSessionStore(sid)
	if err != nil {
		return
	}

	//从session里获取当前登录的用户email
	state := sessions.Get("login_state")
	if "logined" != state {
		return
	}

	email := sessions.Get("login_email").(string)
	o := orm.NewOrm()
	user := &User{}
	qs := o.QueryTable("user")
	err = qs.Filter("email", email).One(user)
	if err != nil {
		err = errors.New("登录账户不存在!")
		return
	}
	//
	announce := &Announce{UserId: user.Id, Text: text}
	_, err = o.Insert(announce)
	if err != nil {
		err = errors.New("添加广播消息失败!")
		return
	}

	return
}
func AnnounceRemove(sid string, aid int64) (err error) {
	//获取session
	var sessions session.SessionStore
	sessions, err = global.MySessions.GetSessionStore(sid)
	if err != nil {
		return
	}

	//从session里获取当前登录的用户email
	state := sessions.Get("login_state")
	if "logined" != state {
		return
	}

	email := sessions.Get("login_email").(string)
	o := orm.NewOrm()
	user := &User{}
	qs := o.QueryTable("user")
	err = qs.Filter("email", email).One(user)
	if err != nil {
		err = errors.New("登录账户不存在!")
		return
	}

	announce := &Announce{Id: aid}

	_, err = o.Delete(announce)
	if err != nil {
		err = errors.New("删除广播失败!")
		return
	}
	return
}

func AnnounceList(sid string) (ret_list []Announce, err error) {
	beego.Info("AnnounceList: sid = ", sid)
	//获取session
	var sessions session.SessionStore
	sessions, err = global.MySessions.GetSessionStore(sid)
	if err != nil {
		return
	}

	//从session里获取当前登录的用户email
	state := sessions.Get("login_state")
	if "logined" != state {
		return
	}

	email := sessions.Get("login_email").(string)
	o := orm.NewOrm()
	user := &User{}
	qs := o.QueryTable("user")
	err = qs.Filter("email", email).One(user)
	if err != nil {
		beego.Error("AnnounceList: 登录账户不存在")
		err = errors.New("登录账户不存在!")
		return
	}
	_, err = o.QueryTable("announce").All(&ret_list)
	if err != nil {
		beego.Error("AnnounceList: 读取广播列表失败")
		err = errors.New("读取广播列表失败!")
		return
	}
	return
}
